package com.hsd.whb.service.impl;

import com.hsd.whb.entity.Participants;
import com.hsd.whb.enums.ResultEnum;
import com.hsd.whb.exception.HwbException;
import com.hsd.whb.repository.ParticipantsRepository;
import com.hsd.whb.service.ParticipantsService;
import com.wangjiacai.hqlQuery.service.impl.BaseServiceImpl;
import com.wangjiacai.hqlQuery.util.HqlUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class ParticipantsServiceImpl extends BaseServiceImpl implements ParticipantsService {

    @Autowired
    private ParticipantsRepository repository;

    @Override
    public List<Participants> findParticipateList(Pageable pageable, Integer managerId, Participants participants) {
        participants.setManagerId(managerId);
        participants.setDeleted(0);
        return this.find(HqlUtil.getQueryHql(participants), participants, pageable,Participants.class);
    }

    @Override
    public long findParticipateListTotalPages(Integer managerId, Participants participants) {
        participants.setManagerId(managerId);
        participants.setDeleted(0);
        return this.count(HqlUtil.getCountHql(participants), participants);
    }

    @Override
    public Participants findParticipantsById(Integer id) {
        return repository.getOne(id);
    }

    @Override
    public List<Participants> findParticipantsByIdInList(List<Integer> list) {
        return repository.findByIdIn(list);
    }

    @Override
    public Participants findParticipantsByUsername(String username) {
        return repository.findByUsername(username);
    }

    @Override
    public Participants save(Participants participants) {
        validParticipants(participants);
        return repository.save(participants);
    }

    @Override
    public Participants update(Participants participants) {
        return repository.save(participants);
    }

    @Override
    public List<Participants> getParticipateListByName(String username, String existName) {
        List<String> list = new ArrayList<>();
        String[] strings = existName.split(",");
        for (String string : strings) {
            if (!string.equals("")) list.add(string);
        }
        if (list.size() == 0) return repository.findByUsernameLikeAndDeleted(username, 0);
        return repository.findByUsernameLikeAndUsernameNotInAndDeleted(username, list, 0);
    }

    private void validParticipants(Participants participants) {
        if (repository.findByUsername(participants.getUsername()) != null) {
            throw new HwbException(ResultEnum.PRITICIPPATE_USERNAME_EXIST);
        }
        if (repository.findByWorkNumber(participants.getWorkNumber()) != null) {
            throw new HwbException(ResultEnum.PRITICIPPATE_WORKNUMBER_EXIST);
        }
    }
}
